package com.xgzit.xgzmall.cart.interceptor;

import com.xgzit.common.constant.AuthServerConstant;
import com.xgzit.common.constant.CartConstant;
import com.xgzit.common.vo.MemberEntityVo;
import com.xgzit.xgzmall.cart.vo.UserInfoDto;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.UUID;

/**
 * 拦截器
 * 执行方法之前，判断用户的登录状态，并封装传递给controller目标请求
 * 拦截器必须实现 HandlerInterceptor 这个接口
 *
 * @Author xgz
 * @Date 2021-06-14 22:04
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoDto> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从request 里面获取session，引入了 springSession，这个request是包装后的request
        UserInfoDto userInfoDto = new UserInfoDto();
        HttpSession session = request.getSession();
        MemberEntityVo member = (MemberEntityVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (Objects.nonNull(member)) {
            // 用户登录
            userInfoDto.setUserId(member.getId());
        }else {
            // 用户没有登录
        }
        Cookie[] cookies = request.getCookies();
        if (Objects.nonNull(cookies) && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)){
                    userInfoDto.setUserKey(cookie.getValue());
                    userInfoDto.setTempUser(true);
                }
            }
        }
        // 如果没有临时用户，就给它分配一个 userKey
        if (StringUtils.isEmpty(userInfoDto.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoDto.setUserKey(uuid);
        }
        // 要共享的数据放进threadLocal
        threadLocal.set(userInfoDto);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 业务执行之后
     **/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoDto userInfoDto = threadLocal.get();

        if (!userInfoDto.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoDto.getUserKey());
            cookie.setDomain("xgzmall.com");
            // 时间是以秒为单位
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
